package com.roads.engineering.controller;

import java.math.BigDecimal;
import java.util.List;

import com.roads.common.constant.Constants;
import com.roads.common.constant.UserConstants;
import com.roads.common.utils.SecurityUtils;
import com.roads.common.utils.StringUtils;
import com.roads.engineering.domain.summary.SummaryRecord;
import com.roads.engineering.service.ISummaryService;
import com.roads.project.domain.ProInstitutionDetail;
import com.roads.project.domain.ProPeriod;
import com.roads.project.service.IProInstitutionService;
import com.roads.project.service.IProPeriodService;
import com.roads.workflow.domain.WorkflowTaskDelivery;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.roads.common.annotation.Log;
import com.roads.common.core.controller.BaseController;
import com.roads.common.core.domain.AjaxResult;
import com.roads.common.enums.BusinessType;
import com.roads.engineering.domain.EngMeterageMaster;
import com.roads.engineering.service.IEngMeterageMasterService;
import com.roads.common.core.page.TableDataInfo;

/**
 * 工程计量Controller
 * 
 * @author nhp
 * @date 2022-02-25
 */
@RestController
@RequestMapping("/engineering/meterage")
public class EngMeterageMasterController extends BaseController {

    @Autowired
    private IEngMeterageMasterService service;

    @Autowired
    private ISummaryService summaryService;

    @Autowired
    private IProPeriodService periodService;

    @Autowired
    private IProInstitutionService institutionService;

    /**
     * 查询列表
     */
    @PreAuthorize("@ss.hasPermi('engineering:meterage:list')")
    @GetMapping("/list")
    public TableDataInfo list(EngMeterageMaster model) {
        startPage();
        // createBy 设置成当前登录用户，根据用户标段查询数据，排除admin
        if (!SecurityUtils.isAdmin(getUserId())) {
            model.setCreateBy(getUsername());
        }
        List<EngMeterageMaster> list = service.selectModelList(model);
        return getDataTable(list);
    }

    /**
     * 获取详细信息
     */
    @PreAuthorize("@ss.hasPermi('engineering:meterage:query')")
    @GetMapping(value = "/{masterId}")
    public AjaxResult getInfo(@PathVariable("masterId") Long masterId) {
        return AjaxResult.success(service.getModelById(masterId));
    }

    /**
     * 获取保留小数位数
     */
    @GetMapping(value = "/getDecimalPlace/{masterId}")
    public AjaxResult getDecimalPlace(@PathVariable("masterId") Long masterId) {
        AjaxResult ajaxResult = new AjaxResult();
        EngMeterageMaster master = service.getModelById(masterId);
        ProInstitutionDetail institutionDetail = institutionService.getDetailModelByInnerCode(master.getInstitutionCode());
        int decimalPlace = institutionDetail.getDecimalPlace1() == null ? 0 : institutionDetail.getDecimalPlace1();
        ajaxResult.put("decimalPlace", decimalPlace);
        ajaxResult.put("ultraMeasure", institutionDetail.getUltraMeasure());
        return ajaxResult;
    }

    /**
     * 添加计量前验证用户是否在工程计量的流程内
     *
     * @return 结果
     */
    @GetMapping("/validateBeforeMeterageIsWorkflowUser")
    public AjaxResult validateBeforeMeterageIsWorkflowUser() {
        int count = service.getCountWorkflowNodeUserForBeginNode(getUsername());
        if (count == 0) {
            return error("工程计量流程开始节点未发现当前登录用户，请联系管理员进行配置");
        } else if (count > 1){
            return error("系统发现当前登录用户出现在两个或两个以上计量流程开始节点，请联系管理员进行配置");
        }
        return success();
    }

    /**
     * 新增
     */
    @PreAuthorize("@ss.hasPermi('engineering:meterage:add')")
    @Log(title = "工程计量", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody EngMeterageMaster model) {
        // 校验申请编号是否重复
        if (UserConstants.NOT_UNIQUE.equals(service.checkApplyCodeUnique(model))) {
            return AjaxResult.error("新增工程计量'" + model.getApplyCode() + "'失败，申请编号已存在");
        }
        // 如果本期已经汇总批复，将无法进行工程计量
        ProPeriod period = periodService.getPeriodByPeriodName(model.getInstitutionCode(), model.getPeriodName());
        if (Constants.YES.equals(period.getIsLock())) {
            return AjaxResult.error("本期已批复汇总，无法进行工程计量操作");
        }
        return toAjax(service.insert(model));
    }

    /**
     * 修改
     */
    @PreAuthorize("@ss.hasPermi('engineering:meterage:edit')")
    @Log(title = "工程计量", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody EngMeterageMaster model) {
        if (UserConstants.NOT_UNIQUE.equals(service.checkApplyCodeUnique(model))) {
            return AjaxResult.error("修改工程计量'" + model.getApplyCode() + "'失败，申请编号已存在");
        }
        return toAjax(service.update(model));
    }

    /**
     * 删除
     */
    @PreAuthorize("@ss.hasPermi('engineering:meterage:remove')")
    @Log(title = "工程计量", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(service.deleteByIds(ids));
    }

    /**
     * 传送
     *
     * @param delivery 传送对象
     * @return 结果
     */
    @PreAuthorize("@ss.hasPermi('engineering:meterage:delivery')")
    @Log(title = "工程计量", businessType = BusinessType.DELIVERY)
    @PostMapping("/delivery")
    public AjaxResult delivery(@RequestBody WorkflowTaskDelivery delivery) {
        // 传送前验证是否进行汇总
        EngMeterageMaster master = service.getModelByUuid(delivery.getTaskUuid());
        SummaryRecord search = new SummaryRecord();
        search.setCreateBy(SecurityUtils.getUsername());
        search.setInstitutionCode(master.getInstitutionCode());
        search.setPeriodName(master.getPeriodName());
        SummaryRecord summaryRecord = summaryService.getSummaryRecord(search);
        if (StringUtils.isNull(summaryRecord)) {
            return error("请先进行数据汇总操作，查看报表无误后，再进行数据传送");
        }
        return toAjax(service.delivery(delivery));
    }

    /**
     * 锁定
     *
     * @param ids 主键集合
     * @return 结果
     */
    @PreAuthorize("@ss.hasPermi('engineering:meterage:lock')")
    @Log(title = "工程计量", businessType = BusinessType.LOCK)
    @GetMapping("/lock/{ids}")
    public AjaxResult lock(@PathVariable Long[] ids) {
        return toAjax(service.lock(ids));
    }

    /**
     * 解锁
     *
     * @param masterId 主键
     * @return 结果
     */
    @PreAuthorize("@ss.hasPermi('engineering:meterage:unlock')")
    @Log(title = "工程计量", businessType = BusinessType.UNLOCK)
    @GetMapping(value = "/unlock/{masterId}")
    public AjaxResult unlock(@PathVariable("masterId") Long masterId) {
        EngMeterageMaster master = service.getModelById(masterId);
        // 查看本期是否最终批复汇总，如果最终批复汇总，将无法进行解锁操作
        if (summaryService.getSummaryIsApprove(master.getInstitutionCode(), master.getPeriodName())) {
            return error("本期数据已最终批复汇总，请先进行未批复汇总后再进行解锁操作");
        }
        return toAjax(service.unlock(master, masterId));
    }

    /**
     * 获取工程信息
     * 标段名称，工期名称，起始桩号，终止桩号，开工日期，完工日期
     *
     * @param masterId 主表ID
     * @return 结果
     */
    @GetMapping(value = "/getEngMasterInfo/{masterId}")
    public AjaxResult getEngMasterInfo(@PathVariable("masterId") Long masterId) {
        AjaxResult ajaxResult = new AjaxResult();
        EngMeterageMaster master = service.getModelById(masterId);
        ajaxResult.put("institutionName", master.getInstitutionName());
        ajaxResult.put("periodName", master.getPeriodName());
        return ajaxResult;
    }

}
